<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="事务所名称" prop="firmName">
        <el-input
          v-model.trim="queryParams.firmName"
          placeholder="请输入事务所名称"
          clearable
          size="small"
          class="width220"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="事务所执业证书编号" prop="practiceCertificateNo">
        <el-input
          v-model.trim="queryParams.practiceCertificateNo"
          placeholder="请输入事务所执业证书编号"
          clearable
          size="small"
          class="width300"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <el-table
      ref="myTable"
      :data="dataList"
      max-height="600"
      border
      stripe
      fit
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" fixed />
      <el-table-column v-for="item in asyColDataFilet" :label="item.name" :prop="item.value+''" :formatter="formatterVal" :render-header="foo" />
      <el-table-column v-if="colData[0].isTrue" label="操作" fixed="right" width="80">
        <template slot-scope="scope">
          <el-button type="primary" plain size="mini" @click="handleUpdate(scope.row)" v-hasPermi="['office:permission:edit']">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :autoScroll="false"
      @pagination="getList"
    >
      <template v-slot:popover>
        <el-popover
          placement="top-end"
          width="260"
          trigger="hover"
        >
          <!--弹出的菜单内容-->
          <div class="selectMenu">
            <el-checkbox-group v-model="colOptions">
              <el-checkbox v-for="item in colSelect" :key="item" :label="item" class="displayBlock marginBottom10"/>
            </el-checkbox-group>
          </div>
          <el-button slot="reference" size="mini" class="selectBtn">
            <i class="el-icon-menu"></i><i class="el-icon-caret-bottom"></i>
          </el-button>
        </el-popover>
      </template>
    </pagination>
    <!--    事务所权限修改 弹出框-->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="700px"
      append-to-body
      class="permissionDialog"
    >
      <el-tree
        :data="deptOptions"
        show-checkbox
        default-expand-all
        ref="tree"
        node-key="id"
        empty-text="加载中，请稍后"
        :props="defaultProps"
        :default-checked-keys="checkList"
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDataScope">确 定</el-button>
        <el-button @click="cancelDataScope">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listConfigOffice,getOfficePowersByOfficeId,saveOfficePowers } from "@/api/system/office";
  import { utilsFoo } from "@/utils/index";
  export default {
    name: "OfficePermission",
    data() {
      return {
        officeId: '',
        dialogVisible: false,  // 弹框： 查看
        dataList:[],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          firmName: '',
          practiceCertificateNo: '',
        },
        perssionForm: {
          officeId: '',
          powerIds: []
        },
        // 已选择项，即显示对表格列
        colOptions: ['操作'],
        // 多选框的可选择项
        colSelect: ['操作'],
        // isTrue属性存放列的状态
        colData: [
          { name: '操作', isTrue: true },
        ],
        defaultAsyColDataFilet:['事务所执业证书编号','事务所名称','预上传','需要审核数据','业务数据查看','申请财政退回'],  // 请在这里添加默认头部
        // 异步获取到标题部分
        asyColData: [],
        asyColDataFilet:[],
        checkList: [],
        deptOptions: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      };
    },
    beforeUpdate() {
      // 防止动态添加列时 表格乱
      this.$nextTick(() => {
        this.$refs.myTable.doLayout();
      });
    },
    watch: {
      colOptions(newVal, oldVal) {
        if (newVal) {    // 如果有值发生变化，即多选框的已选项变化
          let arr = this.colSelect.filter(i => newVal.indexOf(i) < 0) 	// 未选中
            //  处理固定数据
          this.colData.filter(i => {
            if (arr.indexOf(i.name) !== -1) {  // 匹配到为选中的数据 false
              i.isTrue = false
            } else {
              i.isTrue = true
            }
          });
            //  处理异步加载数据
          this.asyColData.filter(i => {
            if (arr.indexOf(i.name) !== -1) {  // 匹配到为选中的数据 false
                i.isTrue = false
            } else {
                i.isTrue = true
            }
          });
          this.asyColDataFilet = this.asyColData.filter( item =>{
              return item.isTrue
          })
        }
      }
    },
    created() {
      this.colOptions = [];
      this.colData.forEach(item => {
          if(item.isTrue){
              this.colOptions.push(item.name);
          }
      });
      this.officeId = this.$route.query.officeId;  // 从编辑页传过来的id
      this.getList();
    },
    mounted(){
    },
    methods: {
      foo(h,{column}) {
          return utilsFoo(h,{column})
      },
      /** 查询权限列表 */
      getList() {
        const self = this;
        this.loading = true;
        listConfigOffice(this.queryParams).then(
          response => {
            self.asyColData = response.rows[0].head;
            self.asyColData.forEach(function (item,index,arr) {
                self.colSelect.unshift(arr[index].name);
                if( self.defaultAsyColDataFilet.includes(arr[index].name)){
                    arr[index].isTrue = true;
                    self.colOptions.unshift(arr[index].name);
                }else{
                    arr[index].isTrue = false;
                }
            });
            self.asyColDataFilet = this.asyColData.filter( item =>{
              return item.isTrue
            });
            self.dataList = response.rows[0].data;
            self.total = response.total;
            self.loading = false;
          }
        );
      },
      formatterVal(row, column, cellValue, index){
          return cellValue===0||cellValue===1?(cellValue=="0"?'×':'√'):cellValue;
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.roleId)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.approvedPracticeDate = [];
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          firmName: '',
          practiceCertificateNo: ''
        };
        this.handleQuery();
      },
      /** 导出按钮操作 */
      handleExport() {
        // const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有权限数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          // return exportRole(queryParams);
        }).then(response => {
          // this.download(response.msg);
        }).catch(function() {});
      },
      handleUpdate(row) {
        this.dialogVisible = true;
        this.title = row.firm_name + '-权限修改';
        this.perssionForm.officeId = row.office_id;
        getOfficePowersByOfficeId(row.office_id).then(res=>{
          this.checkList=res.data.checked;
          this.deptOptions=res.data.menus;
        });
      },
      // 确定提交
      submitDataScope() {
        let tree = this.$refs.tree;
        this.perssionForm.powerIds = tree.getCheckedKeys().concat(tree.getHalfCheckedKeys());
        this.$confirm('是否确认提交所修改的权限?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(response => {
          saveOfficePowers(this.perssionForm).then(res=>{
            this.$message({
              message: '事务所权限修改成功!',
              type: 'success'
            });
            this.getList();
            this.dialogVisible = false;
          }).catch(function(){
            this.dialogVisible = false;
          });
        }).catch(function() {});
      },
      // 取消按钮（数据权限）
      cancelDataScope() {
        this.dialogVisible = false;
        this.perssionForm = {
          officeId: '',
          powerIds: []
        };
      },
    }
  };
</script>
<style lang="scss" scoped>
  .app-container{
    position: relative;
  }
  /*form 表单 样式设置 start*/
  ::v-deep .el-form-item{
    margin-bottom: 10px;
  }
  ::v-deep label[for='unifiedSocialCreditCode'],
  ::v-deep label[for='nameOfChargePerson'],
  ::v-deep label[for='certificateNoOfResponsity']{
    line-height: 20px;
  }
  ::v-deep .el-input--suffix .el-input__inner {
    padding-right: 10px;
  }
  ::v-deep .el-select .el-input--suffix .el-input__inner {
    padding-right: 30px;
  }
  ::v-deep .el-date-editor .el-range-input{
    width: 62%;
  }
  /*form 表单 样式设置 end*/

  .width220{
    width: 220px;
  }
  .failedContent{
    margin-top: 20px;
    padding: 20px;
    border: 1px dashed #ccc;
    p{
      line-height: 24px;
    }
  }

  ul{
    li{
      display: flex;
      border: 1px solid #dfe6ec;
      p{
        display: inline-block;
        padding: 10px 15px;
        line-height: 26px;
      }
      p:first-child{
        flex: 1;
        border-right: 1px solid #dfe6ec;
        font-weight: 500;
      }
      p:last-child{
        flex: 5;
      }

    }
    li + li{ border-top: none;}
  }
  .permissionDialog{
    ::v-deep .el-dialog__body{
      padding-top: 0;
    }
  }
</style>
